package auth

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"restful-go/internal/utils"
)

// AuthMiddleware 鉴权中间件
func AuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 从请求头部获取 token
		authHeader := c.GetHeader("api-token")
		if authHeader == "" {
			utils.ErrorJSON(c, http.StatusUnauthorized, "Authorization header not provided")
			c.Abort()
			return
		}

		// 解析 token
		claims, err := ParseToken(authHeader)
		if err != nil {
			utils.ErrorJSON(c, http.StatusUnauthorized, "Invalid or expired token")
			c.Abort()
			return
		}

		// 将解析后的 token 载荷存储到请求上下文中
		c.Set("user_id", claims.UserId)
		c.Next()
	}
}
